from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import threading
import enum
import sys
# 帮我们直接运行此文件时，可以加载到上级目录的ui包
sys.path.append("../")

from ui.Ui_bluetooth_assist_widget import Ui_BluetoothAssistWidget
from drivers.driver_bluetooth import *
from common import utils

class BluetoothState(enum.Enum):
    # 默认状态
    DISCONNECTED = 0
    # 扫描状态
    SCANNING = 1
    # 已连接状态
    CONNECTED = 2
     
class BluetoothAssistWidget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_BluetoothAssistWidget()
        self.ui.setupUi(self)
        
        self.current_state = BluetoothState.DISCONNECTED # 初始化成员属性，即蓝牙的连接状态
        self.devices = []
        self.bd = None

        self.init_ui()
        self.init_data()
    
    def connect_bluetooth_handle(self, device):
        device_addr, device_name = device
        # 连接蓝牙设备
        self.bd = BluetoothDataTransfer(device_addr, device_name, 1)  # 替换为目标设备的蓝牙地址和端口号
        if not self.bd.connect():
            print("连接失败")
            return
        print("连接成功")
        # 连接成功后更新状态
        self.update_ui_state(BluetoothState.CONNECTED)
        
        # 收发数据
        try:
            while True:
                byte_data = self.bd.receive_data(1024)  # 接收数据
                if byte_data:
                    msg = utils.decode_data(byte_data)
                    self.ui.textEdit_recieve.append(msg)
                else:
                    # 主动调佣disconnect或设备被动断开时，或接收的数据为空时
                    break
        except Exception as e:
            print(e)
        finally:
            print("蓝牙设备已断开")
            self.bd = None
            self.update_ui_state(BluetoothState.DISCONNECTED)

    def on_send_clicked(self):
        # 取出需要发送的数据
        text = self.ui.textEdit_send.toPlainText()
        print(text)
        if text == "":
            QMessageBox.warning(self, "警告", "请先输入发送的数据")
            return
        if self.bd == None:
            QMessageBox.warning(self, "警告", "请先连接设备")
            return
        # 发送的文本为字符串文本，默认""UTF-8"编码
        self.bd.send_data(f"{text}\n")
        
    def on_connect_click(self):
        if self.current_state == BluetoothState.SCANNING:
            return
        if self.current_state == BluetoothState.CONNECTED:
            self.bd.disconnect()
            self.update_ui_state(BluetoothState.DISCONNECTED)
            return
        # 读取cb_devices中选中的蓝牙设备
        device_index = self.ui.cb_devices.currentIndex()
        print(device_index)
        if device_index == -1:
            print("没有选中蓝牙设备, 请重新选择")
            return
        print("设备", self.devices[device_index])
        
        device_addr, device_name = self.devices[device_index]
        device = self.devices[device_index]
        
        # 创建守护线程来执行收发数据处理
        thread = threading.Thread(target=self.connect_bluetooth_handle, args=(device,), daemon=True)
        thread.start()    

    def init_ui(self):
        self.ui.btn_refresh.clicked.connect(self.init_data)
        self.ui.btn_connect.clicked.connect(self.on_connect_click)
        self.ui.btn_send.clicked.connect(self.on_send_clicked)
        
        # 隐藏已连接设备
        self.ui.gb_connected.setHidden(True)
    
    def get_all_devices(self):
        self.devices = BluetoothDataTransfer.scan_devices()
        print("蓝牙设备扫描完成")
        print("扫描到的蓝牙设备：", self.devices, "共找到", len(self.devices), "个蓝牙设备")
        
        # 扫描完成后更新状态
        self.update_ui_state(BluetoothState.DISCONNECTED)
        
        device_name = []
        for device in self.devices:
            name = device[1]
            if name == "":
                name = "UnKnow"
            device_name.append(name)
        self.ui.cb_devices.addItems(device_name)
        print("蓝牙设备添加完成")     
            
    def update_ui_state(self, new_state: BluetoothState):
        """
        根据当前状态更新UI
        """
        self.current_state = new_state
        # 默认状态
        if self.current_state == BluetoothState.SCANNING:
            self.ui.btn_refresh.setEnabled(False)  # 禁用扫描按钮  
            # self.ui.btn_connect.setEnabled(False)  # 禁用连接按钮
            self.ui.btn_connect.setText("扫描中...")
        
        # 扫描状态
        elif self.current_state == BluetoothState.CONNECTED:
            self.ui.btn_refresh.setEnabled(True)  # 启用扫描按钮
            self.ui.btn_connect.setText("断开连接(已连接)")
            self.ui.label_status.setPixmap(QPixmap(":/icon/connect"))
            # 显示已连接设备
            self.ui.gb_connected.show()
    
        # 已连接状态   
        elif self.current_state == BluetoothState.DISCONNECTED:
            self.ui.btn_refresh.setEnabled(True)  # 启用扫描按钮
            self.ui.btn_connect.setEnabled(True)  # 启用连接按钮
            self.ui.btn_connect.setText("连接设备")
            self.ui.label_status.setPixmap(QPixmap(":/icon/disconnect"))
            
            # 隐藏已连接设备
            self.ui.gb_connected.hide()
            
        if self.bd is not None:
            self.ui.label_connect_name.setText(f"设备：{self.bd.target_name}")
            self.ui.label_connect_addr.setText(f"地址：{self.bd.target_address}")
            
    def init_data(self):
        print("扫描蓝牙设备")
        self.update_ui_state(BluetoothState.SCANNING)   #更新状态
        
        thread = threading.Thread(target=self.get_all_devices, daemon=True)
        thread.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = BluetoothAssistWidget()
    window.show()

    sys.exit(app.exec_())